﻿using System.Collections.Generic;
using System.Web.UI;
using PaceR.Core.Interfaces;
using PaceR.Web.UI.Controls;
using PaceR.Core.Factories;

namespace PaceR.Web.UI
{
    public class MessageDisplayContainer
    {
        protected MessageDisplay _messageDisplay;
        protected IResultObjectFactory _factory;

        protected MessageDisplayContainer(MessageDisplay messageDisplay)
        {
            _messageDisplay = messageDisplay;
            _factory = GetFactory();
        }

        public virtual void AddMessage(string message, ResultMessageTypes messageClass)
        {
            if (_messageDisplay != null)
            {
                var msg = _factory.GetResultMessageObject();
                msg.Message = message;
                msg.MessageType = messageClass;
                _messageDisplay.AddMessage(msg);
            }
        }

        public virtual void AddResults(IResultMessages results)
        {
            if (_messageDisplay != null)
                _messageDisplay.AddMessages(results.AllMessages);
        }

        public virtual bool HasErrors()
        {
            if (_messageDisplay != null)
                return _messageDisplay.HasErrors();
            return false;
        }

        public static MessageDisplayContainer GetMessageDisplay(Control parent, string messageDisplayControlName)
        {
            MessageDisplayContainer container = null;
            MessageDisplay messageDisplay = parent.FindControl(messageDisplayControlName) as MessageDisplay;
            if (messageDisplay != null || parent.Parent == null)
                container = new MessageDisplayContainer(messageDisplay);
            else
                container = GetMessageDisplay(parent.Parent, messageDisplayControlName);
            return container;
        }

        /// <summary>
        /// Returns a factory object used to create concrete IResultMessage objects
        /// </summary>
        /// <returns></returns>
        protected virtual IResultObjectFactory GetFactory()
        {
            return new SimpleResultObjectFactory();
        }
    }
}
